﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Traceability.Register.Writer.API.Controllers
{
    /// <summary>
    /// 上传控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UploadssController : ControllerBase
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<UploadssController> logger;
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="logger">日志</param>
        public UploadssController(ILogger<UploadssController> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
       public async Task<string> Upload(IFormFile file)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return "请选择一个文件";
                }

                var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Uploads");
                if (!Directory.Exists(uploadsFolder))
                {
                    Directory.CreateDirectory(uploadsFolder);
                }

                var filePath = Path.Combine(uploadsFolder, file.FileName);
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                    stream.Flush();
                }

                return "Uploads/" + file.FileName;
            }
            catch (Exception ex)
            {
                logger.LogError("上传文件失败"+ex.Message);
                throw;
            }
        }
    }
}
